package com.imcrl.piano.mvc.model
{
	import flash.display.Sprite;
	import flash.media.Sound;
	import flash.utils.Dictionary;
	
	public class SoundModel
	{
		public var sounds:Dictionary;
		
		public function SoundModel()
		{
			sounds=new Dictionary();
			
			defaults();
		}
		
		protected function defaults():void{
			//todo regist;
		}
		
		
		public function regist(key:int,sound:Sound):void{
			if(sound==null){
				sounds[key]=null;
				return;
			}
			
			var delegate:SingleSoundDelegate=sounds[key];
			if(delegate==null){
				delegate=new SingleSoundDelegate(sound);
			}else{
				delegate.setSound(sound);
			}
			sounds[key]=delegate;
		}
		
		
		public function playByKey(key:int):void{
			sounds[key].play();
		}
		public function stopByKey(key:int):void{
			sounds[key].stop();
		}
		
		/**
		 * 清理旧数据; 
		 * 
		 */		
		public function clear():void{
			for(var key:String in sounds){
				sounds[key].dispose();
				sounds[key]=null;
				delete sounds[key];
			}
		}
		
	}
}
import flash.events.TimerEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.utils.Timer;
import flash.utils.getTimer;


class SingleSoundDelegate{
	private var channel:SoundChannel;
	private var sound:Sound;
	private var timer:Timer;
	
	
	protected var isrunning:Boolean=false;
	public function SingleSoundDelegate(sound:Sound){
		this.sound=sound;
		
		timer=new Timer(15,20);
		timer.addEventListener(TimerEvent.TIMER,timerTickHandler);
	}
	
	public function setSound(value:Sound):void{
		this.sound=value;
	}
	
	public function play():void{
		if(isrunning){
			trace("正在运行,不用重复");
			return;
		}
		
		isrunning=true;
		
		channel=this.sound.play();
	}
	
	public function stop():void{
		if(isrunning==false){
			trace("没有运行,不能停止");
			return;
		}
		isrunning=false;
		
		timer.reset();
		timer.start();
	}
	
	
	private function timerTickHandler(event:TimerEvent):void{
		var soundtf:SoundTransform =channel.soundTransform;
		var m:Number=soundtf.volume -=0.02;
		
		channel.soundTransform=soundtf;
	
		if(m<0.02){
			channel.stop();
			timer.stop();
		}
	}
	public function dispose():void{
		if(this.isrunning){
			channel.stop();
			timer.stop();
		}
	}
}